/* eslint-disable prettier/prettier */
import { createHiveForm, createHiveSimulateForm } from '@/service/modules/integration-assets';
import {
  DataTableColumns,
  FormInst,
  NButton, NDataTable,
  NForm,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui';
import { defineComponent, h, ref, watchEffect } from 'vue';
import styles from './create-hive.module.scss'

const props = {
  schemaNameList: {
    type: Array,
    default() {
      return []
    }
  },
  propModal: {
    type: Boolean,
    default: true
  },
  value: {
    type: Boolean,
    default: false
  }
}

const createHive = defineComponent({
  name: 'createHive',
  props,
  emits: ['closeModal'],
  setup(props, { emit }) {
    const hiveForm = ref({
      tableName: '',
      tableDisc: '',
      schemaName: undefined,
      tecOwnerUserId: '',
      busiOwnerUserId: '',
      deptId: '',
      lifecycleDays: '',
      securityLevel: '',
      dwLevel: undefined,
      hiveSql: '',
      hiveTableFields: []
    })

    const rules = {
      tableName: { required: true, message: '请输入表英文名', trigger: 'blur' },
      tableDisc: { required: true, message: '请输入表描述', trigger: 'blur' },
      schemaName: { required: true, message: '请选择库名', trigger: 'change' },
      tecOwnerUserId: {
        required: true,
        message: '请输入技术负责人',
        trigger: 'blur'
      },
      busiOwnerUserId: {
        required: true,
        message: '请输入业务负责人',
        trigger: 'blur'
      },
      deptId: { required: true, message: '请输入负责部门', trigger: 'blur' },
      lifecycleDays: {
        required: true,
        message: '请输入生命周期',
        trigger: 'blur'
      },
      securityLevel: {
        required: true,
        message: '请输入安全级别',
        trigger: 'blur'
      },
      dwLevel: { required: true, message: '请选择所在层级', trigger: 'change' },
      hiveTableFields: { required: true, message: '请输入字段', trigger: 'blur' }
    }

    const schemaNameOptions = ref([])

    const dwLevelOptions = ref([
      { label: 'ODS', value: 'ODS' },
      { label: 'DWD', value: 'DWD' },
      { label: 'DIM', value: 'DIM' },
      { label: 'DWS', value: 'DWS' },
      { label: 'ADS', value: 'ADS' }
    ])

    const message = useMessage()

    const hiveSubmit = function () {
      hiveFormRef.value?.validate((err) => {
        if (!err) {
          // @ts-ignore
          createHiveForm({...hiveForm.value, busiOwnerUserId: Number(hiveForm.value.busiOwnerUserId), lifecycleDays: Number(hiveForm.value.lifecycleDays), tecOwnerUserId: Number(hiveForm.value.tecOwnerUserId), deptId: Number(hiveForm.value.deptId), hiveTableFields: list.value})
            .then((res: any) => {
              message.success(res.msg ? res.msg : '创建成功')
              emit('closeModal')
            })
            .catch((err: any) => {
              message.error(err.msg ? err.msg : '接口未知错误')
            })
        }
      })
    }

    const resetHive = function () {
      hiveFormRef.value?.restoreValidation()
      hiveForm.value = {
        tableName: '',
        tableDisc: '',
        // @ts-ignore
        schemaName: '',
        tecOwnerUserId: '',
        busiOwnerUserId: '',
        deptId: '',
        lifecycleDays: '',
        securityLevel: '',
        // @ts-ignore
        dwLevel: '',
        hiveSql: '',
        hiveTableFields: []
      }
    }

    const hiveFormRef = ref<FormInst | null>(null)

    const onCloseModal = function () {
      emit('closeModal', true)
    }

    watchEffect(() => {
      // @ts-ignore
      schemaNameOptions.value = props.schemaNameList
    })

    type RowData = {
      key: number
      fieldName: string
      type: string | number
      length: string
      sql: string
      comment: string
      actions: string
    }

    const createData = (): RowData[] => [
      {
        key: 0,
        fieldName: 'John Brown',
        type: 2,
        length: 'New York No. 1 Lake Park',
        sql: 'New York No. 1 Lake Park',
        comment: '',
        actions: 'New York No. 1 Lake Park'
      },
      {
        key: 1,
        fieldName: 'Jim Green',
        type: 4,
        length: 'London No. 1 Lake Park',
        sql: 'London No. 1 Lake Park',
        comment: '',
        actions: 'London No. 1 Lake Park'
      },
      {
        key: 2,
        fieldName: 'Joe Black',
        type: 1,
        length: 'Sidney No. 1 Lake Park',
        sql: 'Sidney No. 1 Lake Park',
        comment: '',
        actions: 'Sidney No. 1 Lake Park'
      }
    ]

    const list = ref(createData())
    const createColumns = (): DataTableColumns<RowData> => [
      {
        title: '字段名',
        key: 'fieldName',
        width: 160,
        render (row, index) {
          return h(NInput, {
            value: row.fieldName,
            onUpdateValue (v) {
              list.value[index].fieldName = v
            }
          })
        }
      },
      {
        title: '类型',
        key: 'type',
        width: 200,
        render (row, index) {
          return h(
            NSelect, {
              value: row.type,
              onUpdateValue (v) {
                list.value[index].type = v
              },
              options: [
                {value: 0, label: 'BOOLEAN'},
                {value: 1, label: 'INT'},
                {value: 2, label: 'TINYINT'},
                {value: 3, label: 'SMALLINT'},
                {value: 4, label: 'BIGINT'},
                {value: 5, label: 'DOUBLE'},
                {value: 6, label: 'FLOAT'},
                {value: 7, label: 'DEICIMAL'},
                {value: 8, label: 'STRING'},
                {value: 9, label: 'VARCHAR'},
                {value: 10, label: 'CHAR'},
                {value: 11, label: 'BINARY'},
                {value: 12, label: 'TIMESTAMP'},
                {value: 13, label: 'DATA'},
                {value: 14, label: 'INTERVAL'},
                {value: 15, label: 'ARRAY'},
                {value: 16, label: 'MAP'},
                {value: 17, label: 'STRUCT'},
                {value: 18, label: 'UNION'}
              ]
          })
        }
      },
      {
        title: '长度',
        key: 'length',
        width: 160,
        render (row, index) {
          return h(NInput, {
            value: row.length,
            onUpdateValue (v) {
              list.value[index].length = v
            }
          })
        }
      },
      {
        title: '生成规则SQL',
        key: 'sql',
        render (row, index) {
          return h(NInput, {
            value: row.sql,
            type: 'textarea',
            onUpdateValue (v) {
              list.value[index].sql = v
            }
          })
        }
      },
      {
        title: '操作',
        key: 'actions',
        render (row, index) {
          return h(
            NButton,
            {
              size: 'small',
              onClick: () => {
                // @ts-ignore
                message.success(index)
                list.value.splice(index, 1)
              }
            },
            { default: () => '删除' }
          )
        }
      }
    ]

    const hiveSQLCreate = function() {
      list.value.push({
        fieldName: '',
        // @ts-ignore
        type: null,
        length: '',
        sql: '',
        actions: ''
      })
    }

    const hiveSimulate = function() {
      message.success('数据模拟');
      hiveFormRef.value?.validate((err) => {
        if (!err) {
          // @ts-ignore
          createHiveSimulateForm({...hiveForm.value, busiOwnerUserId: Number(hiveForm.value.busiOwnerUserId), lifecycleDays: Number(hiveForm.value.lifecycleDays), tecOwnerUserId: Number(hiveForm.value.tecOwnerUserId), deptId: Number(hiveForm.value.deptId), hiveTableFields: list.value})
            .then((res: any) => {
              message.success(res.msg ? res.msg : '数据模拟成功')
            })
            .catch((err: any) => {
              message.error(err.msg ? err.msg : '接口未知错误')
            })
        }
      })
    }

    const onlyAllowNumber = function (value: string) {
      return !value || /^\d+$/.test(value)
    }

    return {
      hiveForm,
      rules,
      dwLevelOptions,
      schemaNameOptions,
      hiveSubmit,
      resetHive,
      hiveFormRef,
      message,
      onCloseModal,
      columns: createColumns(),
      list,
      hiveSQLCreate,
      hiveSimulate,
      onlyAllowNumber
    }
  },
  render() {
    return (
      <NSpace vertical>
        <NModal
          v-model:show={this.$props.propModal}
          preset='card'
          class={styles['modal-hive']}
          title='新建Hive表'
          size='huge'
          bordered={false}
          on-close={this.onCloseModal}
        >
          <NForm
            model={this.hiveForm}
            rules={this.rules}
            label-placement='left'
            ref='hiveFormRef'
          >
            <NFormItem label='表英文名' label-width='120px' path='tableName'>
              <NInput
                v-model:value={this.hiveForm.tableName}
                placeholder='表英文名'
              ></NInput>
            </NFormItem>
            <NFormItem label='表描述' label-width='120px' path='tableDisc'>
              <NInput
                v-model:value={this.hiveForm.tableDisc}
                placeholder='表描述'
              ></NInput>
            </NFormItem>
            <NFormItem label='库名' label-width='120px' path='schemaName'>
              <NSelect
                v-model:value={this.hiveForm.schemaName}
                placeholder='库名'
                options={this.schemaNameOptions}
              ></NSelect>
            </NFormItem>
            <NFormItem
              label='技术负责人'
              label-width='120px'
              path='tecOwnerUserId'
            >
              <NInput
                v-model:value={this.hiveForm.tecOwnerUserId}
                allowInput={this.onlyAllowNumber}
                placeholder='技术负责人'
              ></NInput>
            </NFormItem>
            <NFormItem
              label='业务负责人'
              label-width='120px'
              path='busiOwnerUserId'
            >
              <NInput
                v-model:value={this.hiveForm.busiOwnerUserId}
                allowInput={this.onlyAllowNumber}
                placeholder='业务负责人'
              ></NInput>
            </NFormItem>
            <NFormItem label='负责部门' label-width='120px' path='deptId'>
              <NInput
                v-model:value={this.hiveForm.deptId}
                allowInput={this.onlyAllowNumber}
                placeholder='负责部门'
              ></NInput>
            </NFormItem>
            <NFormItem
              label='生命周期'
              label-width='120px'
              path='lifecycleDays'
            >
              <NInput
                v-model:value={this.hiveForm.lifecycleDays}
                allowInput={this.onlyAllowNumber}
                placeholder='生命周期'
              ></NInput>
            </NFormItem>
            <NFormItem
              label='安全级别'
              label-width='120px'
              path='securityLevel'
            >
              <NInput
                v-model:value={this.hiveForm.securityLevel}
                placeholder='安全级别'
              ></NInput>
            </NFormItem>
            <NFormItem label='所在层级' label-width='120px' path='dwLevel'>
              <NSelect
                v-model:value={this.hiveForm.dwLevel}
                placeholder='所在层级'
                options={this.dwLevelOptions}
              ></NSelect>
            </NFormItem>
            {/*<NFormItem label='SQL' label-width='120px' path='hiveSql'>*/}
            {/*  <NInput*/}
            {/*    v-model:value={this.hiveForm.hiveSql}*/}
            {/*    placeholder='SQL'*/}
            {/*    type='textarea'*/}
            {/*  ></NInput>*/}
            {/*</NFormItem>*/}
            <NFormItem path='hiveSql'>
              <NButton onClick={this.hiveSQLCreate}>新增</NButton>
            </NFormItem>
            <NFormItem path='hiveSql'>
              <NDataTable
                columns={this.columns}
                data={this.list}
              ></NDataTable>
            </NFormItem>
            <NFormItem>
              <NSpace>
                <NButton onClick={this.hiveSubmit}>立即创建</NButton>
                {/*<NButton onClick={this.hiveSimulate}>数据模拟生成</NButton>*/}
                <NButton onClick={this.resetHive}>重置</NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </NModal>
      </NSpace>
    )
  }
})

export default createHive
